﻿using ZYCommon;
using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace TextEditor
{
    

    public class A_Open : A_Action
    {
        public override string ActionName()
        {
            return "open";
        }

        public override bool Execute()
        {
            if (base.Param1.ToUpper().EndsWith("XML"))
            {
                if (!base.myOwnerDocument.FromXMLFile(base.Param1))
                {
                    return false;
                }                
            }
            else
            {
                StreamReader reader = new StreamReader(base.Param1);
                string strData = reader.ReadToEnd();
                reader.Close();
                strData = StringCommon.FromBase64String(strData);
                XmlDocument document = new XmlDocument();
                document.PreserveWhitespace = true;
                document.LoadXml(strData);
                if (document.DocumentElement != null)
                {
                    base.myOwnerDocument.BeginUpdate();
                    base.myOwnerDocument.FromXML(document.DocumentElement);
                }
            }
            base.myOwnerDocument.Modified = false;
            base.myOwnerDocument.EndUpdate();          
            return true;
        }

        public override bool UIExecute()
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.CheckFileExists = true;
                dialog.Title = "打开文件";
                dialog.ShowReadOnly = false;
                dialog.Filter = "XML文件或Base64编码文件|*.xml;*.txt|所有文件|*.*";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    base.Param1 = dialog.FileName;
                    return this.Execute();
                }
            }
            return true;
        }
    }
}

